package com.itbac.springsecurityoauth2demo.controller;

import com.itbac.springsecurityoauth2demo.pojo.Constant;
import com.itbac.springsecurityoauth2demo.pojo.User;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/3/27 12:09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    //http://localhost:8080/user/getCurrentUser
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication,HttpServletRequest request){
        //返回认证的主体 User 类
        User user = (User) authentication.getPrincipal();
        System.out.println("user:"+user.toString());
        //把密码去掉，不能返回用户的QQ密码给新浪
        user.setPassword(null);
        //还可以封装其他信息返回。
        return user;
    }
    //把请求头的信息，传进来，解析再响应。
    @RequestMapping("/getJwtInfo")
    public Object getJwtInfo(HttpServletRequest request){
        String header = request.getHeader("Authorization");
        String token = header.substring(header.lastIndexOf("Bearer") + 7);
        return Jwts.parser().setSigningKey(Constant.salt.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
        /**
         *
         {
         "user_name": "bac",
         "scope": [
         "all"
         ],
         "name": "张三",
         "exp": 1616885528,
         "authorities": [
         "admin"
         ],
         "jti": "40eaca55-09a7-48ac-b21f-3cbb17fd2954",
         "client_id": "admin"
         }
         */
    }
}
